package cn.genmer.test.security.polygon;

import com.alibaba.fastjson.JSONObject;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;

import java.util.ArrayList;
import java.util.List;

public class PolygonSplitter2 {

    public static void main(String[] args) throws ParseException {
        GeometryFactory geometryFactory = new GeometryFactory();

        // 示例多边形（经纬度数组格式）
        String polygonCoordinates = "[[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0], [0.0, 0.0]]";
        Polygon polygon = createPolygonFromCoordinates(polygonCoordinates, geometryFactory);

        // 示例线（经纬度数组格式）
        String lineCoordinates = "[[2.0, -1.0], [2.0, 5.0]]";
        LineString line = createLineStringFromCoordinates(lineCoordinates, geometryFactory);

        // 分割多边形
        List<Polygon> splitPolygons = splitPolygon(polygon, line);

        // 打印分割后的多边形
        for (Polygon splitPolygon : splitPolygons) {
            List<List<double[]>> polygonCoordinatesList = convertPolygonToCoordinatesArray(splitPolygon);
            for (List<double[]> coordinates : polygonCoordinatesList) {
                System.out.println(JSONObject.toJSONString(coordinates));
            }
        }
    }

    public static Polygon createPolygonFromCoordinates(String coordinates, GeometryFactory geometryFactory) throws ParseException {
        // 将数组格式转换为WKT格式的坐标点字符串
        String[] points = coordinates.split("],");
        StringBuilder wktCoordinates = new StringBuilder();
        for (String point : points) {
            String[] xy = point.replaceAll("\\[|\\]", "").split(",");
            wktCoordinates.append(xy[0]).append(" ").append(xy[1]).append(",");
        }
        // 移除最后一个逗号
        wktCoordinates.deleteCharAt(wktCoordinates.length() - 1);

        WKTReader reader = new WKTReader(geometryFactory);
        Polygon polygon = (Polygon) reader.read("POLYGON((" + wktCoordinates + "))");
        return polygon;
    }

    public static LineString createLineStringFromCoordinates(String coordinates, GeometryFactory geometryFactory) throws ParseException {
        // 将数组格式转换为WKT格式的坐标点字符串
        String[] points = coordinates.split("],");
        StringBuilder wktCoordinates = new StringBuilder();
        for (String point : points) {
            String[] xy = point.replaceAll("\\[|\\]", "").split(",");
            wktCoordinates.append(xy[0]).append(" ").append(xy[1]).append(",");
        }
        // 移除最后一个逗号
        wktCoordinates.deleteCharAt(wktCoordinates.length() - 1);

        WKTReader reader = new WKTReader(geometryFactory);
        LineString line = (LineString) reader.read("LINESTRING(" + wktCoordinates + ")");
        return line;
    }

    public static List<Polygon> splitPolygon(Polygon polygon, LineString line) {
        GeometryFactory geometryFactory = polygon.getFactory();

        // 计算多边形和线的差集，以分割多边形
        Geometry difference = polygon.difference(line);

        // 处理 GeometryCollection
        List<Polygon> splitPolygons = new ArrayList<>();
        if (difference instanceof GeometryCollection) {
            for (int i = 0; i < difference.getNumGeometries(); i++) {
                Geometry geometry = difference.getGeometryN(i);
                if (geometry instanceof Polygon) {
                    splitPolygons.add((Polygon) geometry);
                }
            }
        } else if (difference instanceof Polygon) {
            splitPolygons.add((Polygon) difference);
        }

        return splitPolygons;
    }

    public static List<List<double[]>> convertPolygonToCoordinatesArray(Polygon polygon) {
        List<List<double[]>> result = new ArrayList<>();
        Coordinate[] coordinates = polygon.getCoordinates();
        List<double[]> polygonCoordinates = new ArrayList<>();
        for (Coordinate coordinate : coordinates) {
            polygonCoordinates.add(new double[]{coordinate.getX(), coordinate.getY()});
        }
        result.add(polygonCoordinates);
        return result;
    }
}
